<template>
  <div>
    <div class="emailLeftBox">
      <a-form-model
        ref="ruleForm"
        :model="basicInfo"
        class="ant-advanced-search-form"
        :rules="rules"
        style="width:450px;padding:36px 12px 36px 24px;"
      >
        <dev class="titleSty">{{ $t('yxsz') }}</dev>
        <div class="newEditStyle AsteriskAfter ">
          <a-form-model-item
            :label="$t('serverAaddress')"
            prop="server"
          >
            <a-input v-model="basicInfo.server">
            </a-input></a-form-model-item>
          <a-row :gutter="24">
            <a-col
              :md="12"
              :sm="24">
              <a-form-model-item
                :label="$t('serverPort')"
                prop="port"
              >
                <a-input-number v-model="basicInfo.port" />
              </a-form-model-item>
            </a-col>
            <a-col
              :md="12"
              :sm="24">
              <!-- 使用ssl安全连接 -->
              <a-form-model-item
                label=" "
              >
                <a-checkbox
                  :checked="basicInfo.enableSsl"
                  @change="onChange"
                >{{ $t('enableSSL') }}</a-checkbox>
              </a-form-model-item>
            </a-col>
          </a-row>
          <a-form-model-item
            :label="$t('sendDomain')"
            prop="domain"
          >
            <a-input v-model="basicInfo.domain" />
          </a-form-model-item>
          <a-form-model-item
            :label="$t('userName')"
            prop="username"
          >
            <a-input v-model="basicInfo.username" />
          </a-form-model-item>
          <a-form-model-item
            :label="$t('sender')"
            prop="userEmail"
          >
            <a-input v-model="basicInfo.userEmail" />
          </a-form-model-item>
          <a-form-model-item
            :label="$t('serverPassword')"
            prop="password"
          >
            <a-input
              v-model="basicInfo.password"
              type="password"
            />
          </a-form-model-item>
        </div>
        <div style="position: absolute;bottom: 16px;">
          <auth-button
            type="primary"
            :auth="managePerms.mailSet.edit"
            :loading="loading"
            :disabled="submitDisabled"
            @click="handleSubmit">
            {{ $t('save') }}
          </auth-button>
          <a-button style="margin-left:8px" @click="cancelBack">{{ $t('cancel') }}</a-button>
        </div>
      </a-form-model>
    </div>
    <div class="emailRightBox">
      <div class="leftbtn">
        <dev class="titleSty">邮件模板设置</dev>
        <s-table
          ref="flowConfigTable"
          :columns="columns"
          :data="loadData"
          :showPagination="false"
          rowKey="key"
          :scroll="{x:400,y:400}"
          :customRow="customRow"
          :rowClassName="rowClassName"
        >
          <template slot="businessType" slot-scope="text">
            <table-ellipsis :text="text"></table-ellipsis>
          </template>
        </s-table>
        <h3 style="margin-top: 10px;">{{mailTemplatesName}}</h3>
        <div class="messageContent" v-html="msg"></div>
      </div>
      <div class="rightbtn">
        <auth-button type="primary" :ghost="true" size="small" @click="handleAdd">新建邮件模板</auth-button>
        <auth-button @click="handleEdit" type="primary" :ghost="true" size="small">编辑邮件模板</auth-button>
        <auth-button @click="deleteList" type="primary" :ghost="true" size="small">删除邮件模板</auth-button>
      </div>
    </div>
    <email-template-edit ref="mailTemplates" :emailTemplateInfo="emailTemplateInfo" :titles="titles" @flushed="refreshData" @againValue="againValue"></email-template-edit>
  </div>
</template>
<script>
import { managePerms } from '@/config/permission/index'
import AuthButton from '@/components/AuthButton'
import { checkTextLen } from '@/utils/validate'
import EmailTemplateEdit from './components/emailTemplateEdit.vue'
import STable from '@/components/Table/index'
import { emailTbColumns } from './config/list'
import tableEllipsis from '@/components/Ellipsis/TableEllipsis'

export default {
  name: 'MailSet',
  components: { AuthButton, EmailTemplateEdit, STable, tableEllipsis },
  data () {
    return {
      managePerms,
      basicInfo: {},
      submitDisabled: false,
      loading: false,
      rules: {
        server: [
          { required: true, message: this.$t('pleaseInput') },
          { validator: checkTextLen(200) },
          {
            validator: (rule, value, callback) => {
              const reg = /^(?=^.{3,255}$)[a-zA-Z0-9][-a-zA-Z0-9]{0,62}(\.[a-zA-Z0-9][-a-zA-Z0-9]{0,62})+$/
              if (value && !reg.test(value)) {
                callback(new Error(this.$t('fwqdz')))
                return
              }
              callback()
            }
          }
        ],
        port: [
          { required: true, message: this.$t('pleaseInput') },
          {
            validator: (rule, value, callback) => {
              if (value < 0 || value > 65535) {
                callback(new Error(this.$t('portInputTip')))
                return
              }
              callback()
            }
          },
          { validator: checkTextLen(50) }
        ],
        domain: [
          { required: true, message: this.$t('pleaseInput') },
          { validator: checkTextLen(200) }
        ],
        username: [
          { required: true, message: this.$t('pleaseInput') },
          { validator: checkTextLen(50) }
        ],
        userEmail: [
          { required: true, message: this.$t('pleaseInput') },
          { validator: checkTextLen(50) }
        ],
        password: [
          { required: true, message: this.$t('pleaseInput') },
          { validator: checkTextLen(20) }
        ]
      },
      columns: emailTbColumns,
      // 当前选中table行的id
      tableCurrRowId: '',
      // 邮件模板信息
      emailTemplateInfo: {},
      titles: '',
      msg: '',
      transitParameters: '',
      // 用于删除判断
      businessType: '',
      mailTemplatesName: '邮件模板名称'
    }
  },
  created () {
    this.mailDetail()
    this.$store.dispatch('getEmailMessageTemplateBusinessTypeDictCodeData')
  },
  methods: {
    loadData () {
      const vm = this
      const apiPromise = vm.$api.getEmailMessageTemplateList()
      return new Promise((resolve, reject) => {
        return apiPromise.then((res) => {
          resolve(res)
        }).catch((err) => {
          reject(err)
        })
      })
    },
    // 点击行
    customRow (record, index) {
      return {
        on: {
          click: () => {
            this.transitParameters = { ...record }
            this.tableCurrRowId = record.id
            this.businessType = record.businessType
            this.msg = record.title + record.message
            this.mailTemplatesName = record.name
          }
        }
      }
    },
    // 行高亮
    rowClassName (record, index) {
      return (record.id === this.tableCurrRowId) ? 'blue' : 'white'
    },
    // 用于再次传值
    againValue () {
      this.emailTemplateInfo = this.transitParameters
    },
    // 新建
    handleAdd () {
      this.titles = 'new'
      this.$refs.mailTemplates.shutDown()
    },
    // 编辑
    handleEdit () {
      this.emailTemplateInfo = this.transitParameters
      if (this.emailTemplateInfo && this.emailTemplateInfo.id) {
        this.titles = 'edit'
        this.$refs.mailTemplates.shutDown()
      } else {
        this.$message.error('请选中模板后，再进行编辑！')
      }
    },
    // 删除
    deleteList () {
      if (this.tableCurrRowId === '') {
        this.$message.error('请选中模板后，再进行删除！')
        return
      }
      if (this.businessType !== '无业务关联-暂存') {
        this.$message.error('已被业务模块关联并使用的邮件模板不可删除！')
        return
      }
      const vm = this
      this.$confirm({
        title: '请确定是否删除该邮件模板？',
        content: '邮件模板删除后将不可恢复，已被业务模块关联并使用的邮件模板不可删除！',
        class: 'confirmStyle',
        width: 378,
        onOk () {
          vm.$api.deleteEmailMessageTemplate({ ids: [vm.tableCurrRowId] }).then(() => {
            vm.msg = ''
            vm.mailTemplatesName = ''
            vm.$message.success(vm.$t('successfullyDelete'))
            vm.refreshData() // 刷新页面
          })
        },
        onCancel () { }
      })
    },
    // 刷新
    refreshData (val) {
      this.$refs.flowConfigTable.refresh(false)
      // 保存后更新邮件模板内容
      if (val) {
        this.$api.getEmailMessageTemplateDetail({ id: val }).then((res) => {
          console.log(res.data, 'res.data')
          this.transitParameters = res.data
          this.msg = res.data.title + res.data.message
          this.mailTemplatesName = res.data.name
        })
      }
    },
    mailDetail () {
      const vm = this
      vm.$api.getMailDetail({}).then(res => {
        if (res.data) {
          vm.basicInfo = res.data
        }
      })
    },
    onChange (e) {
      this.$set(this.basicInfo, 'enableSsl', e.target.checked)
      this.submitDisabled = false
    },
    handleSubmit () {
      // e.preventDefault()
      const vm = this
      this.$refs.ruleForm.validate((valid) => {
        if (valid) {
          vm.loading = true
          vm.$api
            .editMailDetail(vm.basicInfo)
            .then(() => {
              vm.loading = false
              vm.$message.success(vm.$t('success'))
            })
            .catch(() => {
              vm.loading = false
            })
        }
      })
    },
    cancelBack () {
      this.mailDetail()
      this.$refs.ruleForm.clearValidate()
    }
  }
}
</script>
<style scoped lang="less">
.emailLeftBox{
  float: left;
}
.emailRightBox{
  width:550px;
  padding:36px 0px 36px 35px;
  float: left;
  .leftbtn{
    width: 400px;
  float: left;
    .messageContent {
    overflow:auto;
    width: 100%;
    padding: 10px;
    height: 250px;
    margin-top: 10px;
    border:1px solid #ccc
  }

  }
  .rightbtn {
  padding-top:50px;
  float: left;
  .ant-btn{
    display: block;
    margin-bottom: 10px;
    border-radius:0;
    border: 1px #ccc solid;
    color: #000;
    font-size: 12px;
  }
}
}
.titleSty {
  font-size: 22px;
  height: 50px;
  display: block;
}
 /deep/.ant-table-tbody .white{
    background-color: white !important;
  }
  /deep/.ant-table-tbody .blue{
    background-color: #ccc !important;
  }
  /deep/.ant-table-tbody > tr:hover:not(.ant-table-expanded-row):not(.ant-table-row-selected) > td {
  //自定义table行hover上去的背景颜色
    background: #ccc;
    cursor: default;
  }
</style>
